<script setup lang="ts">
import { nextTick, onMounted, reactive, ref } from "vue";
import { useState } from "../../../hooks/index.js";
import { getMenuListApi, addroleListApi, editRoleApi } from "../../../api/auth";
import { ElMessage } from "element-plus";
import { roleListApi, editRoleListApi } from "@/api/auth";
// ================
const emit = defineEmits(["updateList"]);
const isShow = ref(false);
const treeRef = ref();
const formRef = ref()
const list = ref([]);
const id = ref(0)
// 表单数据
const defaultState = {
  description: "", //角色描述
  name: "", //角色名称
  status: 1, //角色状态
  menus: [], //需要节点和半节点

};
const formData = ref({ ...defaultState });
// =================
// 验证规则
const formRules = {
  description: [{ required: true, message: "请选择", trigger: "blur" }],
  name: [{ required: true, message: "请选择", trigger: "blur" }],
  status: [{ required: true, message: "请选择", trigger: "change" }],
  menus: [{ required: true, message: "请选择", trigger: "change" }],
};
// 获取数据转为树
onMounted(async () => {
  let res = await getMenuListApi();
  res.data = transListToTreeData(res.data, 0);
  list.value = res.data;
});
// 整理选中的树
const changeHandler = () => {
  // 2. 整理数据
  // console.log(toRaw(treeRef.value.getCheckedKeys())); //它将返回当前选中节点 key 的数组
  // console.log(toRaw(treeRef.value.getHalfCheckedKeys())); //则返回目前半选中的节点的 key 所组成的数组
  formData.value.menus = [...treeRef.value.getCheckedKeys(), ...treeRef.value.getHalfCheckedKeys()]
}
// ============
// 表单提交
const onSubmit = async () => {
  // 表单校验
  await formRef.value.validate();
  // 处理数据
  if (formData.value.id) {
    formData.value.default_data = 1
    formData.value.update_time = new Date()
  }
  // 发送请求
  formData.value.id ?
    await editRoleApi(formData.value) :
    await addroleListApi(formData.value)
  // 提示
  ElMessage.success(formData.value.id ? '修改成功' : '添加成功')
  // 更新列表
  emit("updateList");
  // 关闭弹框
  isShow.value = false
}
// 弹窗关闭的回调
const closeHandler = async () => {

  // 重置数据
  formData.value = {
    description: "", //角色描述
    name: "", //角色名称
    status: 1, //角色状态
    menus: [], //需要节点和半节点
  }
  treeRef.value.setCheckedKeys([])
  await nextTick()
  // 移除校验
  formRef.value.resetFields();
}
// 回显事件
const replyData = async (id) => {

  formData.value.id = id
  let res = await editRoleListApi(id)
  // console.log(res);
  // res.data.menuList = transListToTreeData(res.data.menuList, 0);
  // const editList = res.data;
  function fn(arr, ret) {
    arr.forEach(e => {
      if (!e.children) {
        ret.push(e.id)
      } else {
        fn(e.children, ret)
      }
    })
    return ret
  }
  res.data.menuList = fn(res.data.menuList, [])
  Object.assign(formData.value, res.data)/////////////
  treeRef.value.setCheckedKeys(res.data.menuList)
}

/**
 *
 * 列表型数据转化树形
*/
function transListToTreeData(list, rootValue) {
  const arr = []
  list.forEach(item => {
    if (item.pid === rootValue) {
      // 找到了匹配的节点
      // 当前节点的id 和 当前节点的子节点的pid是想等的
      const children = transListToTreeData(list, item.id) // 找到的节点的子节点
      if (children.length) item.children = children  // 将子节点赋值给当前节点
      arr.push(item)
    }
  })
  return arr
}

defineExpose({
  isShow,
  replyData
})


</script>
<template>
  <div>
    <el-drawer v-model="isShow" size="50%" title="添加角色" @close="closeHandler">
      <el-form ref="formRef" label-width="80px" label-position="top" :model="formData" :rules="formRules">
        <el-row :gutter="20">
          <el-col :span="10">
            <el-form-item label="角色名称" prop="name">
              <el-input placeholder="请输入" v-model="formData.name"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="角色描述" prop="description">
              <el-input placeholder="请输入" v-model="formData.description"></el-input> </el-form-item></el-col>
        </el-row>
        <div style="height: 40px"></div>
        <el-row :gutter="20">
          <el-col :span="10">
            <el-form-item label="权限表标识" prop="menus">

              <el-tree class="mx-4" @check-change="changeHandler" ref="treeRef" :data="list" :props="{ label: 'title' }"
                show-checkbox node-key="id" highlight-current />

            </el-form-item>
          </el-col>
          <el-col :span="10">
            <div />
            <el-form-item label="启用状态" prop="status">
              <el-radio-group v-model="formData.status" class="ml-4">
                <el-radio v-for="item in useState()" :key="item.value" size="large" :label="item.value">
                  {{ item.label }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <template #footer>
        <div style="flex: auto">
          <el-button @click="isShow = false">取消</el-button>
          <el-button type="primary" @click="onSubmit">确认</el-button>
        </div>
      </template>
    </el-drawer>
  </div>
</template>

<style scoped></style>
